package com.dx.chat.server;

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.Socket;

/**
 * Description: 服务器启动的主线程
 *
 * @author rockstarsteve
 * @version 1.0
 * @copyright Copyright (c) 电信
 * @since 2023/9/8
 */
@Slf4j
public class ServerThread extends Thread {

    private ServerInfoBean serverInfoBean;

    public ServerThread(ServerInfoBean serverInfoBean) {
        this.serverInfoBean = serverInfoBean;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Socket socket = serverInfoBean.getServerSocket().accept();
                InetAddress inetAddress = socket.getInetAddress();
                String hostAddress = inetAddress.getHostAddress();
                serverInfoBean.getIpSocketMap().put(hostAddress, socket);
                new SocketConnectionThread(socket, serverInfoBean).start();
                serverInfoBean.setChatInfoString(serverInfoBean.getChatInfoString() + "客户端 " + socket.getInetAddress() + "已连接...\n");
            } catch (Exception ex) {
                log.error("连接服务出错：{}", ex);
            }
        }
    }
}
